import { login, getInfo, getUserInfo, getUserDetails } from '@/api/user'
import { getToken, setToken, removeToken, setAvatar, getAvatar, removeAvatar, setnickName, getnickName, removeName } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: getAvatar(),
  avatar: getnickName(),
  introduction: '',
  roles: [],
  mfAgent: null
}

const mutations = {
  SET_MF_AGENT: (state, mfAgent) =>{
    state.mfAgent = mfAgent
  },
  SET_TOKEN: (state, token) => {
    state.token = `Bearer ${token}`
  },
  // SET_INTRODUCTION: (state, introduction) => {
  //   state.introduction = introduction
  // },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  // SET_ACCOUNT: (state, account) => {
  //   state.account = account
  // }
}

const actions = {
  // user login
  login({ commit }, authCode) {
    return new Promise((resolve, reject) => {
      getUserInfo(authCode).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.oaToken)
        commit('SET_NAME', data.nick)
        commit('SET_AVATAR', data.avatar_url)
        setToken(data.oaToken)
        setnickName(data.nick)
        setAvatar(data.avatar_url)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          reject('Verification failed, please Login again.')
        }

        const { roles, name, avatar, introduction } = data

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }

        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },


  getUserDetail({ commit, state }) {
    return new Promise((resolve, reject) => {
      getUserDetails().then(response => {
        const { data } = response
        if (data.role_code) {
          commit('SET_ROLES', [data.role_code])
        }else{
          commit('SET_ROLES', [])
        }
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, dispatch }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      commit('SET_NAME', '')
      commit('SET_AVATAR', '')
      removeToken()
      removeAvatar()
      removeName()
      resetRouter()
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_NAME', '')
      commit('SET_AVATAR', '')
      commit('SET_ROLES', [])
      removeToken()
      removeAvatar()
      removeName()
      resolve()
    })
  },

  // dynamically modify permissions 修改角色
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  },

  setMfAgent({ commit }, mfAgent) {
    return new Promise(resolve => {
      commit('SET_MF_AGENT', mfAgent)
      resolve(true)
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
